const api = {
	get: (url, data) => uni.request({
		url,
		data,
		header: {}
	}),
	post: (url, data) => uni.request({
		url,
		data,
		method: 'POST',
		header: {}
	}),
	delete: (url, data) => uni.request({
		url,
		data,
		method: 'DELETE',
		header: {}
	}),
	put: (url, data) => uni.request({
		url,
		data,
		method: 'PUT',
		header: {}
	}),
}

export default api;

function isPromise(obj) {
	return (
		!!obj &&
		(typeof obj === "object" || typeof obj === "function") &&
		typeof obj.then === "function"
	);
}
uni.addInterceptor('request', {
	invoke(args) {
		uni.showLoading({
			title: '加载中'
		});
		args.url = 'http://120.77.87.175' + args.url;
		args.header['Authorization'] = `Bearer ${uni.getStorageSync('token')}` || ''
	},
	returnValue(res) {
		uni.hideLoading();

		if (!isPromise(res)) {
			return res;
		}
		let returnValue = null;
		return res
			.then((res) => {
				if (res.data.code === 401) {
					uni.showToast({
						title: '登录过期',
						duration: 2000,
						icon: 'error',
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/index'
						})
					}, 2000)

				}
				returnValue = res.data;
			})
			.catch((err) => {
				uni.showToast({
					title: err.msg,
					duration: 2000,
					icon: 'error'
				});
				returnValue = err;
			})
			.then(() => returnValue);
	},
})